package in.muton.edushare.registration;

import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.PropertyModel;

import com.edushare.common.dao.EmailTemplatesDAO;
import com.edushare.common.dao.UsersDAO;
import com.edushare.common.vo.EmailTemplates;
import com.edushare.common.vo.Users;

import in.muton.edushare.EduSharePage;

public class ForgotPassword extends EduSharePage{
	private Form<Object> f;
	private String userName = "";
	public ForgotPassword(){
		super();
		f = new Form<Object>("form"){
			private static final long serialVersionUID = -1962142947447306062L;
			@Override
			public void onSubmit(){
				if(getUser()!=null){
					Users user = getUser();
					user.setConfKey(user.getPassword());
					EmailTemplatesDAO emtDAO = new EmailTemplatesDAO(getSessionORMInterface());
					EmailTemplates template = emtDAO.getTemplateObject
						(EmailTemplates.PASSWORD_RETRIEVE_KEY);
					emtDAO.sendPasswordResetMail(template, user, user.getConfKey());
					info("A message has been sent to your email-ID. "+
						"It contains a link to a page where you can reset your password.");
					setVisible(false);
					
				}else{
					error("Unable to find a user with the username/email-ID you provided.");
				}
			}
		};
		add(f);
		add(new FeedbackPanel("feedback"));
		f.add(new TextField<String>("uname", new PropertyModel<String>(this, "userName")));
	}
	
	protected Users getUser() {
		UsersDAO uDAO = new UsersDAO(getSessionORMInterface());
		Users user = uDAO.getUserFromUserName(getUserName());
		if(user != null)
			return user;
		user = uDAO.getUsersByEMail(getUserName());
			return user;
	}
	
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserName() {
		return userName;
	}
}
